<?php
/**
 * Created by PhpStorm.
 * User: yuliang
 * Date: 2017/6/5
 * Time: 下午1:47
 */

namespace app\admin\controller;


use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Controller;
use think\Db;

class Course extends Controller
{
    // 课程列表
    public function courseList(){
        $search = input('search');
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $model = model('Course');
        if(trim($search)){
            $list = $model->field(true)->where('title|subtitle','like','%'.$search.'%')->where('status','neq','-3')->where('type','neq','6')->order('id desc')->page($page,$pageSize)->select();
            $count = $model->field(true)->where('title|subtitle','like','%'.$search.'%')->where('status','neq','-3')->where('type','neq','6')->count();
        }else{
            $list = $model->field(true)->where('type','neq','6')->where('status','neq','-3')->order('create_time desc')->page($page,$pageSize)->select();
            $count = $model->field(true)->where('type','neq','6')->where('status','neq','-3')->count();
        }
        if(!empty($list)){
            $apply = model('Apply');
            foreach ($list as &$value){
                $value['apply'] = $apply->countNumber($value['id']);
            }
        }
        $result['page'] = ceil($count/$pageSize);
        $result['data'] = $list;
        return api_return('操作成功！',$result);
    }

    // 推荐列表
    public function recommendList(){
        $model = model('Course');
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $list = $model->field(true)->where(['recommend'=>1])->order('id desc')->page($page,$pageSize)->select();
        $count = $model->field(true)->where(['recommend'=>1])->count();

        $result['page'] = ceil($count/$pageSize);
        $result['data'] = $list;
        return api_return('操作成功！',$result);
    }

    // 课程详情
    public function detail(){
        $id = input('id');
        $info = model('Course')->field(true)->where('id',$id)->find();
        if(empty($info)){
            return api_error('2005','对不起，该课程不存在！');
        }
       /* if($info['file_url']){
            $info['file_url'] = config('api_host').'/uploads/'.$info['file_url'];
        }*/
        $info['category_name'] = category_name($info['type']);
        $info['apply'] = model('Apply')->where('course_id',$id)->count();
        // 组合课查子集
        $info['child'] = [];
        if($info['type'] ==5){
            $info['child'] = Db::table('jy_course_group')->alias('a')->join('jy_course b','a.child_id = b.id','LEFT')
                ->field('b.*')->where("a.parent_id = $id")->select();
        }
        return api_return('操作成功！',$info);

    }

    // 添加课程
    public function add(){
        // 图片处理
        $files = request()->file('image');
        if($files){
            $files = $files->getInfo();
            $fileInfo = pathinfo($files['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $files['tmp_name'];
            $qiniu = config('qiniu');
            $auth = new Auth($qiniu['access_key'],$qiniu['secret_key']);
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/course/'.date('Ymd').'/'.md5(rand(1000,9999)).'.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('20001',$ret['code'].$err['error']);
            }else{
                $img_url = $qiniu['site_url'].$ret['key'];
            }
        }else{
            return api_error('1000','请选择图片');
        }

        $data = input('post.');
        $data['img_url'] = $img_url;
        $validate = $this->validate($data,'Course');
        if($validate !== true){
            return api_error('1000',$validate);
        }
//        $result = Db::table('jy_course')->strict(true)->insertGetId($data);
        $result = model('Course')->allowField(true)->save($data);
        if($result){
            $id = model('Course')->getLastInsID();
            $child = trim(input('post.child'),',');
            // 如果类型为组合商品，添加到商品关联表中
            if($child && input('post.type') == 5){
                if(strpos($child,',')){
                    $childs = explode(',',$child);
                    $tmp= [
                        'parent_id' => $id,
                        'create_time' => date('Y-m-d H:i:s',time())
                    ];
                    $arr = [];
                    foreach ($childs as $value){
                        $tmp['child_id'] = $value;
                        $arr[] = $tmp;
                    }
                    Db::name('course_group')->insertAll($arr);
                }else{
                    $arr = ['parent_id'=>$id,'create_time'=>date('Y-m-d H:i:s',time()),'child_id'=>$child];
                    Db::name('course_group')->insert($arr);
                }
            }
            return api_return('操作成功！',array());
        }else{
            return api_error('20002','添加课程失败！');
        }
    }

    // 添加课程
    public function edit(){

        $data = input('post.');
        $validate = $this->validate($data,'Course');
        if($validate !== true){
            return api_error('1000',$validate);
        }
        // 图片处理
        $files = request()->file('image');
        if($files){
            $files = $files->getInfo();
            $fileInfo = pathinfo($files['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $files['tmp_name'];
            $qiniu = config('qiniu');
            $auth = new Auth($qiniu['access_key'],$qiniu['secret_key']);
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/course/'.date('Ymd').'/'.md5(rand(1000,9999)).'.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('20003',$err['code'].$err['error']);
            }else{
                $img_url = $qiniu['site_url'].$ret['key'];
            }
            $data['img_url'] = $img_url;
        }
        $data['update_time'] = date('Y-m-d H:i:s');
        $result = model('Course')->isUpdate(true)->allowField(true)->save($data,['id'=>$data['id']]);
        if($result !== false){
            $child = trim(input('post.child'),',');
            // 如果类型为组合商品，添加到商品关联表中
            if($child && input('post.type') ==5){
                // 清除原有数据
                Db::name('course_group')->where('parent_id',$data['id'])->delete();
                if(strpos($child,',')){
                    $childs = explode(',',$child);
                    $tmp= [
                        'parent_id' => $data['id'],
                        'create_time' => date('Y-m-d H:i:s',time())
                    ];
                    $arr = [];
                    foreach ($childs as $value){
                        $tmp['child_id'] = $value;
                        $arr[] = $tmp;
                    }
                    Db::name('course_group')->insertAll($arr);
                }else{
                    $arr = ['parent_id'=>$data['id'],'create_time'=>date('Y-m-d H:i:s',time()),'child_id'=>$child];
                    Db::name('course_group')->insert($arr);
                }
            }
            return api_return('操作成功！',array());
        }else{
            return api_error('20004','修改课程失败！');
        }
    }

    // 操作状态
    public function operate(){
        $data['id'] = trim(input('post.id'),',');
        $data['status'] = input('post.status');
        $rule = [
            'id' => 'require',
            'status' => 'require|in:0,-1,1,2,-2,-3' // 0待审，1上线，2通过，-1下线/删除，-2拒绝 -3删除
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $where['id'] = ['in',$data['id']];
        $result = model('Course')->isUpdate(true)->save(['status'=>$data['status']],$where);
        if($result !== false){
            return api_return('修改状态成功！',array());
        }else{
            return api_error('20006','修改失败！');
        }
    }

    // 删除操作
    public function delCourse(){
        $data['id'] = trim(input('post.id'),',');
        $rule = [
            'id' => 'require',
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $where['id'] = ['in',$data['id']];
        $result = model('Teacher')->isUpdate(true)->save(['status'=>'-3'],$where);
        if($result !== false){
            return api_return('删除成功！',array());
        }else{
            return api_error('20007','删除失败！');
        }
    }

    // 目录列表
    public function catalogList(){
        $course_id = input('course_id');
        $course = model('Course')->field('id,title,teacher_name')->where('id',$course_id)->find()->toArray();
//        dump($course);die;
        if(!empty($course)){
            // 获取课程章节
            $chapter = Db::name('chapter')->field('id,title,course_id,parent_id,video_id,sometimes')->where('course_id',$course_id)->order('id desc')->select();
            if($chapter){
                $parent = [];
                $child = [];
                foreach ($chapter as $key=>$value){
                    if($value['parent_id'] == 0){
                        $parent[] = $value;
                    }else{
                        $child[$value['parent_id']][] = $value;
                    }
                }
                foreach ($parent as $k => $v){
                    if(isset($child[$v['id']])){
                        $parent[$k]['child'] = $child[$v['id']];
                    }else{
                        $parent[$k]['child'] = array();
                    }
                }
                $course['chapter'] = $parent;
            }else{
                $course['chapter'] = array();
            }
            return api_return('操作成功！',$course);
        }else{
            return api_error('20008','对不起，该课程不存在！');
        }

    }

    // 目录批量添加
    public function uploadCatalog(){
        $course_id = input('post.course_id');
        $str = input('post.str');
        $course = model('Course')->field('id,title,teacher_name')->where('id',$course_id)->find();
        if(empty($course)){
            return api_error('20015','对不起，课程不存在！');
        }
        $array = json_decode($str,true);
        $model = model('Chapter');
        $date = date('Y-m-d H:i:s');
        if(!empty($array)){
            foreach ($array as $key => $value){
                $data = [];
                $data['title'] = $value['subject'];
                $data['course_id'] = $course_id;
                $data['parent_id'] = 0;
                $data['video_id'] = '';
                $data['sometimes'] = '';
                $data['create_time'] = $date;
//                $insert = $model->isUpdate(false)->save($data);
//                $id = $model->getLastInsID();
                $id = Db::name('chapter')->insertGetId($data);
                if($id && !empty($value['sons'])){
                    foreach ($value['sons'] as $v){
                        $child = array();
                        $child['title'] = $v['subject'];
                        $child['parent_id'] = $id;
                        $child['video_id'] = $v['id'];
                        $child['course_id'] = $course_id;
                        $child['sometimes'] = $v['timer'];
                        $child['create_time'] = $date;
                        $tmp[] = $child;
                    }
//                    dump($tmp);die;
//                    $result = $model->isUpdate(false)->saveAll($tmp);
                    Db::name('chapter')->insertAll($tmp);
                }
                unset($id,$tmp);
            }

            // 返回已上传的目录结构 获取课程章节
            $chapter = $model->field('id,title,course_id,parent_id,video_id,sometimes')->where('course_id',$course_id)->order('id asc')->select();
            if($chapter){
                $parent = [];
                $child = [];
                foreach ($chapter as $key=>$value){
                    if($value['parent_id'] == 0){
                        $parent[] = $value;
                    }else{
                        $child[$value['parent_id']][] = $value;
                    }
                }
                foreach ($parent as $k => $v){
                    if(isset($child[$v['id']])){
                        $parent[$k]['child'] = $child[$v['id']];
                    }else{
                        $parent[$k]['child'] = array();
                    }
                }
                $course['chapter'] = $parent;
            }else{
                $course['chapter'] = array();
            }
            return api_return('操作成功！',$course);

        }else{
            return api_error('20014','对不起，章节目录不能为空！');
        }
    }

    // 添加章
    public function addChapter(){
        $course_id = input('post.course_id');
        $title = input('post.title');
        if($course_id && $title){
            $result = model('Chapter')->save(['course_id'=>$course_id,'title'=>$title]);
            if($result){
                $data['chapter_id'] = model('Chapter')->getLastInsID();
                return api_return('操作成功！',$data);
            }else{
                return api_error('20009','添加失败！');
            }
        }else{
            return api_error('1000','缺少必要的参数！');
        }
    }

    // 编辑章
    public function editChapter(){
        $chapter_id = input('post.chapter_id');
        $course_id = input('post.course_id');
        $title = input('post.title');
        $rule = [
            'chapter_id' => 'require|number',
            'course_id' => 'require|number',
            'title' => 'require'
        ];
        $validate = $this->validate(input('post.'),$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }

        $result = model('Chapter')->save(['course_id'=>$course_id,'title'=>$title],['id'=>$chapter_id]);
        if($result !== false){
            return api_return('操作成功！',array());
        }else{
            return api_error('20010','修改失败！');
        }

    }

    // 添加节
    public function addSection(){
        $data['parent_id'] = input('post.chapter_id');
        $data['course_id'] = input('post.course_id');
        $data['title'] = input('post.title');
        $data['video_id'] = input('post.video_id');
        $data['sometimes'] = input('post.sometimes');
        $rule = [
            'chapter_id' => 'require|number',
            'course_id' => 'require|number',
            'title' => 'require',
            'video_id' => 'require',
            'sometimes' => 'require'
        ];
        $validate = $this->validate(input('post.'),$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $result = model('Chapter')->allowField(true)->save($data);
        if($result){
            $data['section_id'] = model('Chapter')->getLastInsID();
            return api_return('添加成功！',$data);
        }else{
            return api_error('20011','添加失败！');
        }
    }

    // 编辑节
    public function editSection(){
        $data['id'] = input('post.id');
        $data['parent_id'] = input('post.chapter_id');
        $data['course_id'] = input('post.course_id');
        $data['title'] = input('post.title');
        $data['video_id'] = input('post.video_id');
        $data['sometimes'] = input('post.sometimes');
        $rule = [
            'parent_id' => 'require|number',
            'course_id' => 'require|number',
            'title' => 'require',
            'video_id' => 'require',
            'id' => 'require|number',
            'sometimes' => 'require'
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $result = model('Chapter')->save($data,['id'=>$data['id']]);
        if($result){
            return api_return('修改成功！',array());
        }else{
            return api_error('20012','修改失败！');
        }
    }

    // 删除章／节
    public function deleteCatalog(){
        $id = input('post.id');
        $model = model('Chapter');
        $info = $model->where('id',$id)->value('parent_id');
        // 删除章时判断是否有节
        if($info == 0){
            $child = $model->where('parent_id',$id)->select();
            if(!empty($child)){
                return api_error('20013','该章还有节，无法删除');
            }
        }
        $result = $model->where('id',$id)->delete();
        if($result){
            return api_return('操作成功！',array());
        }else{
            return api_error('20014','对不起，删除失败');
        }
    }

    /**
     * 课程推荐，或取消推荐
     * @return \think\response\Json
     */
    public function recommend(){
        $data['id'] = trim(input('post.id'),',');
        $data['recommend'] = input('post.recommend');
        $data['sort_key'] = input('post.sort_key');
        $rule = [
            'id' => 'require',
            'recommend' => 'require|in:0,1',
            'sort_key' => 'number'
        ];
        $validate = $this->validate($data,$rule);
        if($validate !== true){
            return api_error('1000',$validate);
        }
        $where['id'] = ['in',$data['id']];
        $result = model('Course')->isUpdate(true)->save(['recommend'=>$data['recommend'],'sort_key'=>$data['sort_key']],$where);
        if($result !== false){
            return api_return('操作成功！',array());
        }else{
            return api_error('20015','操作失败！');
        }
    }

    // 课程，供组合课使用
    public function choseCourse(){

        $model = model('Course');
        $list = $model->field('id,title,type')->where('type','neq','5')->where('status','eq','1')->order('id desc')->select();
        $result['data'] = $list;
        return api_return('操作成功！',$result);
    }

    // 课程添加老师
    public function choseTeacher(){
        $teacher = model('Teacher')->field('id,name,type,education')->where('status',1)->select();
        if(!empty($teacher)){
            foreach ($teacher as &$value){
                $value['education'] = json_decode($value['education']);
            }
        }else{
            $teacher = array();
        }
        $result['data'] = $teacher;
        return api_return('操作成功！',$result);
    }

    // 添加电子书
    public function addEbook(){
//        set_time_limit(0);
        $data = [
            'title' => input('post.title'),
            'subtitle' => input('post.subtitle'),
            'description' => input('post.description'),
            'hour' => input('post.hour'),
            'is_free' => input('post.is_free'),
            'sort_key' => input('post.sort_key'),
            'price' => input('post.price'),
            'type' => 6,
            'tags' => input('post.tags')?input('post.tags'):0
        ];
        $rule = [
            'title' => 'require',
            'subtitle' => 'require',
            'description' => 'require',
            'hour' => 'require|number',
            'is_free' => 'number',
            'price' => 'number',
            'sort_key' => 'number'
        ];
        $result = $this->validate($data,$rule);
        if($result != true){
            return api_error('1000',$result);
        }

        // 图片处理
        $files = request()->file('image');
        if($files){
            $files = $files->getInfo();
            $fileInfo = pathinfo($files['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $files['tmp_name'];
            $qiniu = config('qiniu');
            $auth = new Auth($qiniu['access_key'],$qiniu['secret_key']);
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/course/'.date('Ymd').'/'.md5(rand(1000,9999)).'.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('20016',$ret['code'].$err['error']);
            }else{
                $img_url = $qiniu['site_url'].$ret['key'];
            }
        }else{
            return api_error('1000','请选择图片');
        }

        /*// 文件上传到本地
        $upFile = request()->file('upfile');
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $upFile->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            // 成功上传后 获取上传信息
            $file_url = $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            return api_error('20017',$upFile->getError());
        }
        $data['file_url'] = $file_url;*/
        $data['file_url'] = input('post.file_url');
        $data['img_url'] = $img_url;
        $res = model('Course')->save($data);
        if($res){
            return api_return('添加成功！',array());
        }else{
            return api_error('20018','添加失败！');
        }
    }

    // 添加电子书
    public function editEbook(){
        set_time_limit(0);
        $data = [
            'id' => input('post.id'),
            'title' => input('post.title'),
            'subtitle' => input('post.subtitle'),
            'description' => input('post.description'),
            'hour' => input('post.hour'),
            'is_free' => input('post.is_free'),
            'sort_key' => input('post.sort_key'),
            'price' => input('post.price'),
            'type' => 6,
            'tags' => input('post.tags')?input('post.tags'):0
        ];
        $rule = [
            'title' => 'require',
            'subtitle' => 'require',
            'description' => 'require',
            'hour' => 'require|number',
            'is_free' => 'number',
            'price' => 'number',
            'sort_key' => 'number'
        ];
        $result = $this->validate($data,$rule);
        if($result != true){
            return api_error('1000',$result);
        }

        // 图片处理
        $files = request()->file('image');
        if($files){
            $files = $files->getInfo();
            $fileInfo = pathinfo($files['name']);
            $ext = 'jpg';
            if(isset($fileInfo['extension'])){
                $ext = $fileInfo['extension'];
            }
            $file = $files['tmp_name'];
            $qiniu = config('qiniu');
            $auth = new Auth($qiniu['access_key'],$qiniu['secret_key']);
            $token = $auth->uploadToken($qiniu['bucket']);
            // 构建 UploadManager 对象
            $uploadMgr = new UploadManager();
            $fileName = 'upload/course/'.date('Ymd').'/'.md5(rand(1000,9999)).'.'.$ext;
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token,$fileName,$file);
            if($err !== null){
                return api_error('20020',$ret['code'].$err['error']);
            }else{
                $data['img_url'] = $qiniu['site_url'].$ret['key'];
            }
        }

        /*// 文件上传到本地
        $upFile = request()->file('upfile');
        if($upFile){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $upFile->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息
                $data['file_url'] = $info->getSaveName();
            }else{
                // 上传失败获取错误信息
                return api_error('20021',$upFile->getError());
            }
        }*/
        $data['file_url'] = input('post.file_url');
        $res = Db::name('course')->where(['id'=>$data['id']])->update($data);
        if($res !== false){
            return api_return('修改成功！',array());
        }else{
            return api_error('20019','修改失败！');
        }
    }

    // 电子书列表
    public function ebookList(){
        $page = input('page')?input('page'):1;
        $pageSize = 10;
        $model = Db::name('course');
        $where['status'] = ['neq',-3];
        $where['type'] = ['eq',6];
        $result['data'] = $model->field(true)->where($where)->order('id desc')->page($page,$pageSize)->select();
        $count = $model->field(true)->where($where)->count();
        $result['page'] = ceil($count/$pageSize);
        return api_return('操作成功！',$result);
    }

    // 上传测试
    public function uploadTest(){
        $file = request()->file('file');
        dump($file);die;
    }
}